<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------


// 加载框架引导文件
require __DIR__ . '/../vendor/autoload.php';
use Symfony\Component\DomCrawler\Crawler;

use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;


$url = 'https://www.cxta.com/35493.html';

$client = new GuzzleHttp\Client(['verify' =>false]);//关闭安全验证
$promise = $client->requestAsync('GET',$url,['allow_redirects' => false]);//创建请求
//设置回调
$promise->then(
    function (ResponseInterface $res) {
        echo '1';
        //echo $res->getStatusCode() . "\n";
        $html = (String)$res->getBody();
        //echo $html;
        //preg_match_all('/window.location.replace\(\"(\w+_*.*)*\"\)/',$html,$match,PREG_PATTERN_ORDER);
        //var_dump($match);
        $crawler = new Crawler($html);
        $title = $crawler->filterXPath('descendant-or-self::title')->first();
        var_dump($title->text());
        $crawler->filterXPath('descendant-or-self::p')->each(function($node,$i){
            echo '<p>'.$node->html().'</p>';
        });
    },
    function (RequestException $e) {
        echo '2';
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);
//等待响应
$promise->wait();
// 'application/json; charset=utf8'
/*
$html = (String)$res->getBody();
//echo $html;
//内容部分获取
$crawler = new Crawler($html);
//title
$title = $crawler->filterXPath('//*[@id="title_area"]/h1')->text();
echo '<h1>'.$title.'</h1>';
$crawler->filter('p')->each(function($node,$i){
	echo $node->html();
});



/*

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
    'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'

// 发送一个异步请求
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();
*/